<template>
    <view class="irrigation-container">
        <!-- 使用封装的页面头部组件 -->
        <page-header title="智能灌溉"></page-header>

        <view class="tabs-container">
            <view
                class="tab"
                :class="{ active: currentMode === 'irrigation' }"
                @click="switchMode('irrigation')">
                <text class="tab-text">智能灌溉</text>
            </view>
            <view
                class="tab"
                :class="{ active: currentMode === 'drainage' }"
                @click="switchMode('drainage')">
                <text class="tab-text">智能排水</text>
            </view>
        </view>

        <!-- 地块选择 -->
        <view class="land-selector-container">
            <view class="section-title">选择地块</view>
            <view class="land-grid">
                <view
                    class="land-item"
                    v-for="block in irrigationData[currentMode]"
                    :key="block.id"
                    :class="{ active: selectedBlock === block.id }"
                    @click="selectBlock(block.id)">
                    <image src="/static/images/cao.png" mode="aspectFill"></image>
                    <text>{{ block.name }}</text>
                </view>
            </view>
        </view>

        <!-- 地块详细控制 -->
        <view class="block-detail" v-if="selectedBlock">
            <view class="section-title">水阀控制</view>
            <view class="block-header">
                <view class="mode-switch">
                    <text
                        class="mode-option"
                        :class="{ active: getBlockById(selectedBlock).allOn }"
                        @click="showConfirmDialog(selectedBlock, 'all')">
                        阀门全开
                    </text>
                    <text
                        class="mode-option"
                        :class="{ active: !getBlockById(selectedBlock).allOn }"
                        @click="showConfirmDialog(selectedBlock, 'all')">
                        阀门全关
                    </text>
                </view>
            </view>

            <!-- 区域控制列表 -->
            <view class="area-list">
                <view class="area-item" v-for="area in getBlockAreas(selectedBlock)" :key="area.id">
                    <!-- 区域标题和控制 -->
                    <view class="area-header">
                        <view class="area-info" @click="toggleAreaExpand(selectedBlock, area.id)">
                            <text class="expand-icon" :class="{ expanded: area.expanded }">▶</text>
                            <text class="area-name">{{ area.name }}{{ getModeText() }}状态</text>
                        </view>
                        <view
                            class="area-control"
                            @click="toggleAreaStatus(selectedBlock, area.id)">
                            <text class="status-text">{{ area.on ? '已开启' : '已关闭' }}</text>
                            <view class="switch-container" :class="{ 'switch-on': area.on }">
                                <view class="switch-button"></view>
                            </view>
                            <text class="action-text">{{ area.on ? '关闭' : '开启' }}</text>
                        </view>
                    </view>

                    <!-- 子地块列表 -->
                    <view class="sub-blocks" v-if="area.expanded">
                        <view
                            class="sub-block-item"
                            v-for="subBlock in getAreaSubBlocks(selectedBlock, area.id)"
                            :key="subBlock.id"
                            @click="toggleSubBlockStatus(selectedBlock, subBlock.id)">
                            <view class="sub-block-info">
                                <view
                                    class="status-indicator"
                                    :class="{ active: subBlock.on }"></view>
                                <text class="sub-block-name">
                                    {{ subBlock.name }}{{ getModeText() }}状态
                                </text>
                            </view>
                            <view class="sub-block-control">
                                <text class="status-text">
                                    {{ subBlock.on ? '已开启' : '已关闭' }}
                                </text>
                                <view
                                    class="switch-container"
                                    :class="{ 'switch-on': subBlock.on }">
                                    <view class="switch-button"></view>
                                </view>
                                <text class="action-text">{{ subBlock.on ? '关闭' : '开启' }}</text>
                            </view>
                        </view>
                    </view>
                </view>
            </view>
        </view>
    </view>
</template>

<script>
import PageHeader from '@/components/PageHeader/index.vue'
import irrigationData from './irrigationData.json'
import { valve, land } from '@/utils/api/index.js'
export default {
    data() {
        return {
            currentMode: 'irrigation', // irrigation 或 drainage
            selectedBlock: 1,
            hasWaterAlert: true,
            lands: [],
            // 层级数据结构
            irrigationData: irrigationData,
        }
    },
    onShow() {
        this.fetchParcels()
        this.fetchList()
    },
    methods: {
        /**
         * 获得地块数据
         */
        async fetchParcels() {
            uni.showLoading({ title: '加载地块数据...' })
            const res = await land.getAllParcelAndFields()

            if (res.code === 0 && res.data && res.data.length > 0) {
                // 格式化API返回的数据为组件所需的格式
                this.lands = res.data
            } else {
                // 使用默认数据作为备选
                this.initDefaultData()
            }
            uni.hideLoading()
        },
        /**
         * 获得水阀数据
         */
        async fetchList() {
            // type 0:总进 1：总排
            // parcelId 地块名称
            const res = await valve.getValveParcelList({ parcelId: 1, type: 0 })

            if (res.code === 0 && res.data) {
                console.log('结果数据')
                console.log(res.data)
            }
        },
        goBack() {
            uni.navigateBack()
        },

        switchMode(mode) {
            this.currentMode = mode
            // 保持相同的地块选择，如果不存在则选择第一个
            const blocks = this.irrigationData[mode]
            if (!blocks.find((b) => b.id === this.selectedBlock)) {
                this.selectedBlock = blocks.length > 0 ? blocks[0].id : null
            }
        },

        selectBlock(blockId) {
            this.selectedBlock = blockId
        },

        getBlockById(blockId) {
            return this.irrigationData[this.currentMode].find((block) => block.id === blockId) || {}
        },

        getBlockAreas(blockId) {
            const block = this.getBlockById(blockId)
            return block.areas || []
        },

        getAreaSubBlocks(blockId, areaId) {
            const block = this.getBlockById(blockId)
            const area = block.areas?.find((a) => a.id === areaId)
            return area ? area.subBlocks : []
        },

        getModeText() {
            return this.currentMode === 'irrigation' ? '灌溉' : '排水'
        },

        // 切换地块总状态
        toggleBlockStatus(blockId) {
            const block = this.getBlockById(blockId)
            if (!block) return

            const newStatus = !block.allOn
            block.allOn = newStatus

            // 同步更新所有区域和子地块状态
            if (block.areas) {
                block.areas.forEach((area) => {
                    area.on = newStatus
                    if (area.subBlocks) {
                        area.subBlocks.forEach((subBlock) => {
                            subBlock.on = newStatus
                        })
                    }
                })
            }

            uni.showToast({
                title: `${block.name}${this.getModeText()}系统${newStatus ? '已全开' : '已全关'}`,
                icon: 'none',
            })
        },

        // 切换区域状态
        toggleAreaStatus(blockId, areaId) {
            const block = this.getBlockById(blockId)
            if (!block) return

            const area = block.areas.find((a) => a.id === areaId)
            if (!area) return

            area.on = !area.on

            // 同步更新该区域下所有子地块状态
            if (area.subBlocks) {
                area.subBlocks.forEach((subBlock) => {
                    subBlock.on = area.on
                })
            }

            // 更新地块总状态
            this.updateBlockStatus(block)

            uni.showToast({
                title: `${area.name}${area.on ? '已开启' : '已关闭'}`,
                icon: 'none',
            })
        },

        // 切换区域展开状态
        toggleAreaExpand(blockId, areaId) {
            const block = this.getBlockById(blockId)
            if (!block) return

            const area = block.areas.find((a) => a.id === areaId)
            if (!area) return

            area.expanded = !area.expanded
        },

        // 切换子地块状态
        toggleSubBlockStatus(blockId, subBlockId) {
            const block = this.getBlockById(blockId)
            if (!block) return

            let targetArea = null
            let targetSubBlock = null

            for (const area of block.areas) {
                const subBlock = area.subBlocks?.find((item) => item.id === subBlockId)
                if (subBlock) {
                    targetArea = area
                    targetSubBlock = subBlock
                    break
                }
            }

            if (targetSubBlock && targetArea) {
                targetSubBlock.on = !targetSubBlock.on

                // 更新区域状态
                this.updateAreaStatus(targetArea)
                // 更新地块总状态
                this.updateBlockStatus(block)

                uni.showToast({
                    title: `${targetSubBlock.name}${targetSubBlock.on ? '已开启' : '已关闭'}`,
                    icon: 'none',
                })
            }
        },

        // 更新区域状态
        updateAreaStatus(area) {
            if (!area.subBlocks || area.subBlocks.length === 0) return

            const allOn = area.subBlocks.every((item) => item.on)
            const allOff = area.subBlocks.every((item) => !item.on)

            if (allOn) {
                area.on = true
            } else if (allOff) {
                area.on = false
            }
        },

        // 更新地块总状态
        updateBlockStatus(block) {
            if (!block.areas || block.areas.length === 0) return

            const allOn = block.areas.every((a) => a.on)
            const allOff = block.areas.every((a) => !a.on)

            if (allOn) {
                block.allOn = true
            } else if (allOff) {
                block.allOn = false
            }
        },

        // 显示确认对话框
        showConfirmDialog(blockId, type) {
            if (type === 'all') {
                const block = this.getBlockById(blockId)
                const newStatus = !block.allOn
                const statusText = newStatus ? '全开' : '全关'

                uni.showModal({
                    title: '操作确认',
                    content: `确定要将${
                        block.name
                    }的${this.getModeText()}状态切换为${statusText}吗？`,
                    success: (res) => {
                        if (res.confirm) {
                            this.toggleBlockStatus(blockId)
                        }
                    },
                })
            }
        },
    },
}
</script>

<style lang="scss" scoped>
.irrigation-container {
    padding: 20rpx;
    background-color: rgba(251, 252, 250, 1);
    min-height: 100vh;
}

.header {
    display: flex;
    align-items: center;
    padding: 20rpx 0;
    margin-bottom: 20rpx;
}

.icon-back {
    font-size: 40rpx;
    margin-right: 20rpx;
    color: #333;
}

.title {
    font-size: 36rpx;
    font-weight: bold;
    color: #333;
}

.tabs-container {
    display: flex;
    background-color: #fff;
    border-radius: 12rpx;
    margin-bottom: 20rpx;
    padding: 8rpx;
    position: relative;
}

.tab {
    flex: 1;
    text-align: center;
    padding: 20rpx;
    position: relative;
}

.tab.active {
    background-color: transparent;

    &::after {
        content: '';
        position: absolute;
        bottom: 0;
        left: 50%;
        transform: translateX(-50%);
        width: 40%;
        height: 4rpx;
        background-color: #2d6040;
        border-radius: 2rpx;
    }
}

.tab-text {
    font-size: 28rpx;
    color: #666;
}

.tab.active .tab-text {
    color: #2d6040;
}

.land-selector-container {
    padding: 32rpx;
    background-color: #fff;
    margin-bottom: 20rpx;

    .section-title {
        font-size: 32rpx;
        font-weight: 500;
        color: #333;
        margin-bottom: 20rpx;
    }

    .land-grid {
        display: flex;
        flex-wrap: wrap;
        margin: 0 -10rpx;

        .land-item {
            width: calc(25% - 20rpx);
            margin: 10rpx;
            position: relative;
            border-radius: 8rpx;
            height: 132rpx;
            font-family: OPPOSans, OPPOSans;
            font-weight: 400;
            font-size: 24rpx;
            color: #333333;
            text-align: center;
            background: rgba(227, 227, 227, 0.35);

            image {
                width: 76rpx;
                height: 96rpx;
                margin-top: -20rpx;
                object-fit: cover;
            }

            text {
                position: absolute;
                bottom: 0;
                left: 0;
                right: 0;
                text-align: center;
                padding: 8rpx 0;
            }

            &.active {
                background: rgba(45, 96, 64, 1);
                color: #ffffff;
            }

            .block-status {
                font-size: 20rpx;
                color: #999;
                bottom: -24rpx;

                &.running {
                    color: #2d6040;
                }
            }
        }
    }
}

.block-detail {
    background-color: #fff;
    border-radius: 12rpx;
    padding: 30rpx;
    margin-bottom: 20rpx;
}

.block-header {
    display: flex;
    justify-content: center;
    padding-bottom: 20rpx;
    border-bottom: 2rpx solid #f0f0f0;
    margin-bottom: 20rpx;
}

.block-title {
    font-size: 32rpx;
    font-weight: bold;
    color: #333;
}

.block-control {
    display: flex;
    align-items: center;
}

.control-label {
    font-size: 28rpx;
    color: #666;
    margin-right: 20rpx;
}

.mode-switch {
    margin: 20rpx 0 0 0;
    width: 100%;
    display: flex;
    justify-content: space-between;
    border-radius: 20rpx;
    padding: 4rpx;
}

.mode-option {
    width: 48%;
    padding: 26rpx 0;
    font-size: 28rpx;
    color: #666;
    border-radius: 4rpx;
    background-color: transparent;

    background-color: #e3e3e3;

    display: flex;
    justify-content: center;
}

.mode-option.active {
    background-color: #2d6040;
    color: #fff;
}

.area-list {
    margin-top: 20rpx;
}

.area-item {
    margin-bottom: 20rpx;
}

.area-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    background-color: #f8f8f8;
    border-radius: 8rpx;
    padding: 20rpx;
    margin-bottom: 10rpx;
}

.area-info {
    display: flex;
    align-items: center;
    flex: 1;
}

.expand-icon {
    font-size: 24rpx;
    color: #666;
    margin-right: 15rpx;
    transform: rotate(0deg);
    transition: transform 0.3s;
}

.expand-icon.expanded {
    transform: rotate(90deg);
}

.area-name {
    font-size: 28rpx;
    color: #333;
}

.area-control {
    display: flex;
    align-items: center;
}

.status-text {
    font-size: 24rpx;
    color: #666;
    margin-right: 15rpx;
}

.switch-container {
    position: relative;
    width: 80rpx;
    height: 44rpx;
    background-color: #ddd;
    border-radius: 22rpx;
    margin: 0 15rpx;
    transition: background-color 0.3s;
}

.switch-container.switch-on {
    background-color: #2d6040;
}

.switch-button {
    position: absolute;
    top: 4rpx;
    left: 4rpx;
    width: 36rpx;
    height: 36rpx;
    background-color: #fff;
    border-radius: 50%;
    transition: transform 0.3s;
}

.switch-on .switch-button {
    transform: translateX(36rpx);
}

.action-text {
    font-size: 24rpx;
    color: #2d6040;
}

.sub-blocks {
    margin-left: 40rpx;
    padding-left: 20rpx;
    border-left: 2rpx solid #f0f0f0;
}

.sub-block-item {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 15rpx 20rpx;
    background-color: #fff;
    border-radius: 8rpx;
    margin-bottom: 10rpx;
    border: 2rpx solid #f0f0f0;
}

.sub-block-info {
    display: flex;
    align-items: center;
    flex: 1;
}

.status-indicator {
    width: 16rpx;
    height: 16rpx;
    border-radius: 50%;
    background-color: #ddd;
    margin-right: 15rpx;
}

.status-indicator.active {
    background-color: #2d6040;
}

.sub-block-name {
    font-size: 26rpx;
    color: #333;
}

.sub-block-control {
    display: flex;
    align-items: center;
}

.drainage-monitor {
    background-color: #fff;
    border-radius: 12rpx;
    padding: 30rpx;
    margin-bottom: 20rpx;
}

.monitor-title {
    font-size: 32rpx;
    font-weight: bold;
    color: #333;
    margin-bottom: 20rpx;
}

.monitor-data {
    margin-bottom: 20rpx;
}

.data-item {
    background-color: #f8f8f8;
    border-radius: 8rpx;
    padding: 20rpx;
    margin-bottom: 15rpx;
}

.data-date {
    font-size: 24rpx;
    color: #666;
    margin-bottom: 10rpx;
}

.data-info {
    display: flex;
    justify-content: space-between;
}

.data-row {
    display: flex;
    align-items: center;
}

.data-label {
    font-size: 26rpx;
    color: #666;
    margin-right: 10rpx;
}

.data-value {
    font-size: 26rpx;
    font-weight: bold;
    color: #333;
}

.data-value.warning {
    color: #ff4444;
}

.alert-message {
    display: flex;
    align-items: center;
    background-color: rgba(255, 68, 68, 0.1);
    border: 2rpx solid #ff4444;
    border-radius: 8rpx;
    padding: 20rpx;
}

.alert-icon {
    font-size: 32rpx;
    color: #ff4444;
    margin-right: 15rpx;
}

.alert-text {
    font-size: 26rpx;
    color: #ff4444;
    flex: 1;
}
</style>
